import traceback

import win32gui, win32con
import re
from pynput import keyboard


class WindowMgr:
    """Encapsulates some calls to the winapi for window management"""

    def __init__(self):
        """Constructor"""
        self._handle = []
        self.cache=None
    def find_window(self, class_name, window_name=None):
        """find a window by its class_name"""
        self._handle = win32gui.FindWindow(class_name, window_name)

    def _window_enum_callback(self, hwnd, wildcard):
        '''Pass to win32gui.EnumWindows() to check all the opened windows'''
        if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) != None:
                self._handle.append(hwnd)

    def find_window_wildcard(self, wildcard):
        # if self.cache==None:
        #     self.cache=wildcard
        # wildcard=self.cache
        self._handle = []
        win32gui.EnumWindows(self._window_enum_callback, wildcard)

    def set_foreground(self,handle):
        """put the window in the foreground"""
        done = False

        if handle > 0:
            # self.find_window_wildcard(None)
            win32gui.SendMessage(handle, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE, 0)
            win32gui.SetForegroundWindow(handle)
            done = True
        return done
    #隐藏
    def set_forend(self,handle):
        done = False
        if handle > 0:
            # win32gui.SendMessage(self._handle, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE, 0)
            win32gui.ShowWindow(handle, win32con.SW_MINIMIZE)
            done = True
        return done
    def change(self):

            if len(self._handle) > 0:
                try:
                    for handle in self._handle:
                        iconic = win32gui.IsIconic(handle)
                        # print(iconic)
                        # print(win32gui.IsWindowVisible(self._handle))
                        # print(win32gui.IsWindow(self._handle))
                        # print(win32gui.IsWindowEnabled(self._handle))
                        # print(win32gui.IsChild(self._handle))

                        # self.set_foreground()
                        if iconic == 1:
                            self.set_foreground(handle)
                        else:
                            self.set_forend(handle)
                except Exception as e:
                    traceback.print_exc()
pressList=[]
w=None
def on_press(key):
    pass
    if str(key)=="'`'":
        w.change()
    # print("press"+str(key))
    # pressList.append(key)
    # if pressList.__contains__(keyboard.Key.ctrl_l) and pressList.__contains__(keyboard.Key.tab):
    #     print(pressList)
    #     w.change()
def on_release(key):
    pass
    # print("release"+str(key))
    # pressList.remove(key)

if __name__ == '__main__':
    w = WindowMgr()
    w.find_window_wildcard(".*跨屏协作*")
    with keyboard.Listener(on_press=on_press,on_release=on_release) as listener:
        listener.join()
    #w.change()
